import axios from 'axios';

export const instance = axios.create({
    baseURL: 'http://localhost:3000', 
    timeout: 5000 
});

// 请求拦截器
instance.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`; 
        }
        return config;
    },
    error => {
        console.log(error); 
        return Promise.reject(error);
    }
);

// 响应拦截器
instance.interceptors.response.use(
    response => {
        const res = response.data;
        if (res.code !== 200) {
            console.error(res.message || '请求出错');
            return Promise.reject(new Error(res.message || '请求出错'));
        } else {
            return res;
        }
    },
    error => {
        console.log('err' + error); 
        return Promise.reject(error);
    }
);